//
//  ANOrderPayController.m
//  WeiYiMei
//
//  Created by iMac on 2019/4/13.
//  Copyright © 2019年 liyefu. All rights reserved.
//

#import "ANOrderPayController.h"
#import "MineAddressView.h"
#import "OrderCartView.h"
#import "OrderPayRemView.h"
#import "OrderPayTypeView.h"
#import "MineInfoFooterView.h"
#import "AddressEntity.h"
#import "ANAddressManagerController.h"
#import "WXPayRequestHandler.h"
#import "ANOrderInfoController.h"

@interface ANOrderPayController ()

@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) MineAddressView *addressView;
@property (nonatomic, strong) OrderCartView *orderCartView;
@property (nonatomic, strong) OrderPayRemView *orderPayRemView;
@property (nonatomic, strong) OrderPayTypeView *orderPayTypeView;
@property (nonatomic, strong) MineInfoFooterView *footerView;

@property (nonatomic, strong) AddressEntity *addressEntity;


@property (nonatomic, strong) NSNumber *payType;

// 购物车相关数据
@property (nonatomic, copy) NSString *consumerId;
@property (nonatomic, copy) NSString *consumerName;
@property (nonatomic, copy) NSString *filePath;
@property (nonatomic, copy) NSString *goodsId;
@property (nonatomic, copy) NSString *goodsName;
@property (nonatomic, copy) NSString *memberPrice;
@property (nonatomic, copy) NSString *price;
@property (nonatomic, copy) NSString *summary;
@property (nonatomic, copy) NSString *discount;

@end

@implementation ANOrderPayController

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:ANAddressManagerControllerSelectAddressNotificationName object:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"订单支付";
    self.payType = nil;
    
    if (self.type == ANOrderPayControllerTypeGoodsInfo || self.type == ANOrderPayControllerTypeShoppingCart) {
        [self requestDefaultAddress];
    }
    
    if (self.type == ANOrderPayControllerTypeShoppingCart) {
        [self requestShoppingCartInfo];
    }
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(selectAddressFromAddressManager:) name:ANAddressManagerControllerSelectAddressNotificationName object:nil];
    
    WeakSelf
    [WXApiManager sharedManager].resultHandle = ^(NSString * _Nullable orderId) {
        ANOrderInfoController *vc = [[ANOrderInfoController alloc] init];
        vc.orderId = orderId;
        [weakSelf.navigationController pushViewController:vc animated:YES];
    };
}

// 拼接购物车来的商品参数
- (void)pinGoodsParam:(NSArray *)goodsParamList
{
    NSString *params = @"";
    NSString *paramsName = @"";
    if (goodsParamList.count) {
        NSMutableString *mstring = @"".mutableCopy;
        NSMutableString *mNameString = @"".mutableCopy;
        for (NSDictionary *param in goodsParamList) {
            [mstring appendString:param[@"goodsParamId"]];
            [mstring appendString:@","];
            [mNameString appendString:param[@"paramName"]];
            [mNameString appendString:@","];
        }
        params = [mstring substringToIndex:mstring.length-1];
        paramsName = [mNameString substringToIndex:mNameString.length-1];
    }
    self.paramsId = params;
    self.paramsName = paramsName;
    self.orderCartView.tradeTimeLab.text = String(self.paramsName);
}

- (void)requestDefaultAddress
{
    NSDictionary *body = @{@"memberId":UserUtils.shared.vipId};
    
    [URLManager.shareManager getUrlStr:Api_Get_Default_Address parameters:body entityClass:[AddressEntity class] success:^(NSURLResponse * _Nonnull response, BaseEntity * _Nullable baseEntity, NSDictionary * _Nullable otherResponse) {
        
        if (baseEntity) {
            if (baseEntity.code.intValue == 200) {
                self.addressEntity = baseEntity.data;
                [self updateAddressView];
            }
            else {
                [MBProgressHUD showError:baseEntity.message];
            }
        }
        
    } failure:^(NSURLResponse * _Nullable response, NSError * _Nonnull error) {
        
    }];
}

// 从购物车界面进来调用该接口
- (void)requestShoppingCartInfo
{
    NSDictionary *body = @{
                           @"id":self.shoppingCartId
                           };
    [URLManager.shareManager getUrlStr:Api_Get_ShoppingCart_And_GoodsInfo parameters:body success:^(NSURLResponse * _Nonnull response, id  _Nullable responseObj, NSDictionary * _Nullable otherResponse) {
        
        if (responseObj) {
            if ([responseObj[@"code"] intValue] == 200) {
                NSDictionary *data = responseObj[@"data"];
                NSDictionary *goods = data[@"goods"];
                self.consumerId = goods[@"consumerId"];
                self.consumerName = goods[@"consumerName"];
                self.filePath = goods[@"filePath"];
                self.goodsId = goods[@"goodsId"];
                self.goodsName = goods[@"goodsName"];
                self.memberPrice = goods[@"memberPrice"];
                self.price = goods[@"price"];
                self.summary = goods[@"summary"];
                self.discount = goods[@"discount"];
                NSArray *goodsParamList = data[@"goodsParamList"];
                [self pinGoodsParam:goodsParamList];
                self.orderCartView.shopNameLab.text = self.consumerName;
                [self.orderCartView.tradeIcon sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",SERVERADDRS,self.filePath]] placeholderImage:PlaceHolderImage];
                self.orderCartView.tradeNameLab.text = self.goodsName;
                self.orderCartView.tradeDesLab.text = self.summary;
                self.orderCartView.tradeNumLab.text = [NSString stringWithFormat:@"x%d",self.goodsNum];
                self.orderCartView.payLab.text = [NSString stringWithFormat:@"共%d件，合计：",self.goodsNum];
                NSString *price = UserUtils.shared.isMembership?self.memberPrice:self.price;
                self.orderCartView.payPriceLab.text = [NSString stringWithFormat:@"￥%.2f",price.floatValue*self.goodsNum];
                self.orderCartView.price = self.price;
                self.orderCartView.memberPrice = self.memberPrice;
                
            }
            else {
                [MBProgressHUD showError:responseObj[@"message"]];
            }
        }
        
    } failure:^(NSURLResponse * _Nullable response, NSError * _Nonnull error) {
        
    }];
}

// 生成订单
- (void)requestAddOrder
{
    if (self.payType == nil) {
        [MBProgressHUD showWarning:@"请选择支付方式"];
        return;
    }
    if (self.addressEntity == nil) {
        [MBProgressHUD showWarning:@"请先设置货地址"];
        return;
    }
    NSDictionary *body;
    if (self.type == ANOrderPayControllerTypeGoodsInfo) {
        if (self.goodsInfoEntity.goods.consumer == nil) {
            [MBProgressHUD showError:@"商户信息错误"];
            return;
        }
        NSDictionary *orderDict = @{
                                    @"memberId":UserUtils.shared.vipId,
                                    @"consumerId":self.goodsInfoEntity.goods.consumer.orgId,//商户id（会员信息里返回）
                                    @"goods":@{
                                            @"goodsId":self.goodsInfoEntity.goods.goodsId,
                                            @"price":self.goodsInfoEntity.goods.price,
                                            @"discount":self.goodsInfoEntity.goods.discount,
                                            },
                                    @"dealNum":@(self.goodsNum),//数量
                                    @"payWay":self.payType,
                                    @"state":@0,
                                    @"rem":StringNone(self.orderPayRemView.inputView.text),
                                    @"receContact":self.addressEntity.receContact,
                                    @"receTel":self.addressEntity.receTel,
                                    @"receAddress":self.addressEntity.receAddress
                                    };
        NSString *orderStr = [orderDict yy_modelToJSONString];
        
        body = @{
                 @"orderStr":orderStr,
                 @"goodsParams":StringNone(self.paramsId)
                 };
    }
    else if (self.type == ANOrderPayControllerTypeShoppingCart) {
        
        NSDictionary *orderDict = @{
                                    @"memberId":UserUtils.shared.vipId,
                                    @"consumerId":self.consumerId,//商户id
                                    @"goods":@{
                                            @"goodsId":self.goodsId,
                                            @"price":self.price,
                                            @"discount":self.discount,
                                            },
                                    @"dealNum":@(self.goodsNum),//数量
                                    @"payWay":self.payType,
                                    @"state":@0,
                                    @"rem":StringNone(self.orderPayRemView.inputView.text),
                                    @"receContact":self.addressEntity.receContact,
                                    @"receTel":self.addressEntity.receTel,
                                    @"receAddress":self.addressEntity.receAddress
                                    };
        NSString *orderStr = [orderDict yy_modelToJSONString];

        body = @{
                 @"orderStr":orderStr,
                 @"goodsParams":StringNone(self.paramsId)
                 };
    }    
    [MBProgressHUD showActivityMessage:nil];
    [URLManager.shareManager postUrlStr:Api_Add_Order parameters:body success:^(NSURLResponse * _Nonnull response, id  _Nullable responseObj, NSDictionary * _Nullable otherResponse) {
        [MBProgressHUD hideHUD];
        if (responseObj) {
            if ([responseObj[@"code"] intValue] == 200) {
                NSDictionary *data = responseObj[@"data"];
                NSString *transRecordId = data[@"transRecordId"];
                NSString *orderId = data[@"orderId"];
                NSNumber *payState = data[@"payState"];
                if (payState.intValue == 1) {// 直接成功
                    ANOrderInfoController *vc = [[ANOrderInfoController alloc] init];
                    vc.orderId = orderId;
                    [self.navigationController pushViewController:vc animated:YES];
                }
                else {
                    if (self.payType.intValue == 1) {
                        [[WXApiManager sharedManager] wxPayWithOrderId:orderId transRecordId:transRecordId];
                    }
                    else {
                        
                    }
                }
                
                
            }
            else {
                [MBProgressHUD showError:responseObj[@"message"]];
            }
        }
        
    } failure:^(NSURLResponse * _Nullable response, NSError * _Nonnull error) {
        [MBProgressHUD hideHUD];
    }];
}

- (void)setupSubViews
{
    WeakSelf
    
    self.scrollView = [[UIScrollView alloc] init];
    self.scrollView.alwaysBounceVertical = YES;
    [self.view addSubview:self.scrollView];
    [self.scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
    self.addressView = [[MineAddressView alloc] init];
    [self.scrollView addSubview:self.addressView];
    [self.addressView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.scrollView).offset(7);
        make.left.equalTo(self.scrollView).offset(15);
        make.right.equalTo(self.scrollView).offset(-15);
        make.width.equalTo(@(kScreenW-30));
    }];
    self.addressView.layer.cornerRadius = 4;
    self.addressView.layer.masksToBounds = YES;
    if (self.type == ANOrderPayControllerTypeGoodsInfo || self.type == ANOrderPayControllerTypeShoppingCart) {
        self.addressView.canSelect = YES;
    }
    else {
        self.addressView.canSelect = NO;
    }
    
    self.orderCartView = [[OrderCartView alloc] init];
    [self.scrollView addSubview:self.orderCartView];
    [self.orderCartView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.addressView.mas_bottom).offset(10);
        make.height.equalTo(@(kWidth(200)));
        make.left.right.equalTo(self.addressView);
    }];
    self.orderCartView.type = OrderCartViewNormal;
    self.orderCartView.layer.cornerRadius = 4;
    self.orderCartView.layer.masksToBounds = YES;
    
    self.orderPayRemView = [[OrderPayRemView alloc] init];
    [self.scrollView addSubview:self.orderPayRemView];
    [self.orderPayRemView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.addressView);
        make.top.equalTo(self.orderCartView.mas_bottom).offset(10);
    }];
    self.orderPayRemView.layer.cornerRadius = 4;
    self.orderPayRemView.layer.masksToBounds = YES;
    
    self.orderPayTypeView = [[OrderPayTypeView alloc] init];
    [self.scrollView addSubview:self.orderPayTypeView];
    [self.orderPayTypeView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.addressView);
        make.top.equalTo(self.orderPayRemView.mas_bottom).offset(10);
    }];
    self.orderPayTypeView.layer.cornerRadius = 4;
    self.orderPayTypeView.layer.masksToBounds = YES;
    
    // wx:1 ali:2
    self.orderPayTypeView.selectPayTypeHandler = ^(int type) {
        weakSelf.payType = @(type);
    };
    
    self.footerView = [[MineInfoFooterView alloc] initWithFrame:CGRectMake(0, 0, 0, 100)];
    self.footerView.title = @"立即支付";
    [self.scrollView addSubview:self.footerView];
    [self.footerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.orderPayTypeView.mas_bottom);
        make.left.right.equalTo(self.scrollView);
        make.height.equalTo(@100);
        make.bottom.equalTo(self.scrollView);
    }];
    
    // 支付
    self.footerView.sureHandler = ^{
        if (weakSelf.type == ANOrderPayControllerTypeGoodsInfo || weakSelf.type == ANOrderPayControllerTypeShoppingCart) {
            [weakSelf requestAddOrder];
        }
        if (weakSelf.type == ANOrderPayControllerTypeMineOrder) {
            if (weakSelf.payType.intValue == 1) {// 微信支付
                [[WXApiManager sharedManager] wxPayWithOrderId:weakSelf.orderEntity.orderId transRecordId:weakSelf.orderEntity.transactionRecordId];
            }
            else {
                
            }
        }
    };
    
    [self.addressView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(selectAddress)]];
    
    if (self.type == ANOrderPayControllerTypeGoodsInfo) {
        self.orderCartView.shopNameLab.text = self.goodsInfoEntity.goods.consumer.orgName;
        self.orderCartView.tradeNameLab.text = self.goodsInfoEntity.goods.goodsName;
        self.orderCartView.tradeDesLab.text = self.goodsInfoEntity.goods.summary;
        self.orderCartView.tradeTimeLab.text = String(self.paramsName);
        self.orderCartView.tradeNumLab.text = [NSString stringWithFormat:@"x%d",self.goodsNum];
        self.orderCartView.payLab.text = [NSString stringWithFormat:@"共%d件，合计：",self.goodsNum];
        NSString *price = UserUtils.shared.isMembership?self.goodsInfoEntity.goods.memberPrice:self.goodsInfoEntity.goods.price;
        self.orderCartView.payPriceLab.text = [NSString stringWithFormat:@"￥%.2f",price.floatValue*self.goodsNum];
        self.orderCartView.price = self.goodsInfoEntity.goods.price;
        self.orderCartView.memberPrice = self.goodsInfoEntity.goods.memberPrice;
        NSArray *filePathArray = self.goodsInfoEntity.fileList;
        if (filePathArray.count) {
            NSDictionary *filePathDict = filePathArray.firstObject;
            NSString *filePath = filePathDict[@"filePath"];
            [self.orderCartView.tradeIcon sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",SERVERADDRS,filePath]] placeholderImage:PlaceHolderImage];
        }
        
    }
    if (self.type == ANOrderPayControllerTypeMineOrder) {
        self.orderCartView.shopNameLab.text = self.orderEntity.consumerName;
        self.orderCartView.tradeNameLab.text = String(self.orderEntity.goodsName);
        self.orderCartView.tradeDesLab.text = String(self.orderEntity.summary);
        self.orderCartView.tradeTimeLab.text = String(self.orderEntity.goodsParam);
        self.orderCartView.tradeNumLab.text = [NSString stringWithFormat:@"x%@",self.orderEntity.dealNum];
        self.orderCartView.payLab.text = [NSString stringWithFormat:@"共%d件，合计：",self.orderEntity.dealNum.intValue];
        self.orderCartView.payPriceLab.text = [NSString stringWithFormat:@"￥%.2f",self.orderEntity.deaAmount.floatValue];
        self.orderCartView.price = self.orderEntity.price;
        self.orderCartView.memberPrice = self.orderEntity.memberPrice;
        self.addressView.nameLab.text = String(self.orderEntity.receContact);
        self.addressView.telLab.text = String(self.orderEntity.receTel);
        self.addressView.addressLab.text = String(self.orderEntity.receAddress);
        self.orderPayRemView.text = self.orderEntity.rem;
        [self.orderCartView.tradeIcon sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",SERVERADDRS,self.orderEntity.filePath]] placeholderImage:PlaceHolderImage];
    }
    
}

- (void)updateAddressView
{
    self.addressView.entity = self.addressEntity;
}

- (void)selectAddress
{
    if (self.type == ANOrderPayControllerTypeGoodsInfo || self.type == ANOrderPayControllerTypeShoppingCart) {
        ANAddressManagerController *vc = [[ANAddressManagerController alloc] init];
        vc.canSelect = YES;
        [self.navigationController pushViewController:vc animated:YES];
    }
}

- (void)selectAddressFromAddressManager:(NSNotification *)noti
{
    NSDictionary *info = noti.userInfo;
    AddressEntity *entity = info[@"data"];
    self.addressEntity = entity;
    [self updateAddressView];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
